﻿using CodePlex.TfsPluginSuite.Configuration;
using CodePlex.TfsPluginSuite.Helper;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using System;
using System.Linq;

namespace CodePlex.TfsPluginSuite.Notifications
{
    public class WorkItemAssociationCheckInComment : ISubscriber
    {
        public string Name => typeof(WorkItemAssociationCheckInComment).FullName;

        public SubscriberPriority Priority => SubscriberPriority.High;

        public Type[] SubscribedTypes()
        {
            return new Type[1] { typeof(CheckinNotification) };
        }

        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {
            properties = new ExceptionPropertyCollection();
            statusMessage = String.Empty;
            statusCode = 0;

            //don't run this policy if it is disabled in the config file
            if (TfsPluginSuiteConfigurationManager.Section.WorkItemAssociationPolicy.WorkItemInCommentEnabled)
            {
                try
                {
                    if (notificationEventArgs is CheckinNotification && notificationType == NotificationType.Notification)
                    {
                        var notification = notificationEventArgs as CheckinNotification;

                        using (var tfsHelper = new TfsHelper(requestContext, notification))
                        {
                            var ids = tfsHelper.GetWorkItemOnlyFromComment(notification.Comment);
                            tfsHelper.LinkToChangeset(ids);
                        }
                    }
                }
                catch (Exception e)
                {
                    statusCode = -1;
                    statusMessage += e.ToString();
                    requestContext.Status = e;
                }
            }

            return EventNotificationStatus.ActionPermitted;
        }
    }
}
